package com.zenq.ssm.web.ctrl;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.UUID;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.zenq.ssm.utils.WebAppUtil;

@Controller
public class FileUploadController {

	@RequestMapping("/fileUpload")
	public ModelAndView testFileUpload(
			@RequestParam("desc") String desc, 
			@RequestParam("file") MultipartFile file) throws IOException{
		ModelAndView mav = new ModelAndView("success");
		if (null != file) {
			System.out.println("desc: " + desc);
			System.out.println("OriginalFilename: " + file.getOriginalFilename());
			// 文件存储物理路径，最后带文件分隔符
			// 当前web项目运行的环境(在哪个磁盘的哪个文件夹下面)
			String path = WebAppUtil.getRequest().getServletContext().getRealPath("/");
			System.out.println(path);
			String dirPath = getDateString();
			System.out.println(dirPath);
			String destinationDir = path + dirPath;// 指定上传文件的目标保存路径
			File dir = new File(destinationDir);// 按照年/月/日分层级，效率比较高
			if (!dir.exists()) {//判断文件夹如果不存在就先创建
				dir.mkdirs();
			}
			// 新名称(推荐新上传的文件起一个服务器指定的名称)
			String newFileName = UUID.randomUUID()+file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
			// 开启IO流，复制图片
			File f = new File(destinationDir + newFileName);
			file.transferTo(f);// 将文件复制到目标路径
			// 保存图片显示路径
			mav.addObject("fimg", dirPath+newFileName);
			// 保存图片路径到数据库  dirPath+newFileName
			
		}
		return mav;
	}
	
	private String getDateString() {// "\" "/" d:\workspace\zenq
		String pattern = "yyyy"+File.separatorChar+"MM"+File.separatorChar+"dd"+File.separatorChar;
		SimpleDateFormat sdf = new SimpleDateFormat(pattern);
		return sdf.format(Calendar.getInstance().getTime());
	}
}
